package enterprisePerson

import (
	"context"
	"errors"
	"github.com/google/uuid"
	"github.com/spf13/cast"
	"gorm.io/gorm"
	"insighttracking/common/enum"
	"insighttracking/query/dao"
	"net/http"

	"insighttracking/apps/admin/internal/svc"
	"insighttracking/apps/admin/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
	"os"
)

type ModifyEnterprisePersonByIdApiLogic struct {
	logx.Logger
	ctx     context.Context
	svcCtx  *svc.ServiceContext
	Request *http.Request
}

func NewModifyEnterprisePersonByIdApiLogic(ctx context.Context, svcCtx *svc.ServiceContext, request *http.Request) *ModifyEnterprisePersonByIdApiLogic {
	hostname, _ := os.Hostname()
	return &ModifyEnterprisePersonByIdApiLogic{
		Logger: logx.WithContext(ctx).WithCallerSkip(0).WithFields(
			logx.Field("Log_UUID", uuid.New().String()),
			logx.Field("hostname", hostname)),
		ctx:     ctx,
		svcCtx:  svcCtx,
		Request: request,
	}
}

func (l *ModifyEnterprisePersonByIdApiLogic) ModifyEnterprisePersonByIdApi(req *types.ModifyEnterprisePersonReq) (resp string, err error) {
	// todo: add your logic here and delete this line
	accountType := cast.ToInt64(l.ctx.Value("accountType"))
	enterpriseId := cast.ToInt64(l.ctx.Value("enterpriseId"))
	if accountType != enum.EnterpriseEnum {
		return "", errors.New("只有企业账号才能操作")
	}
	_, err = dao.EnterprisePersonEntity.WithContext(l.ctx).Where(
		dao.EnterprisePersonEntity.EnterpriseID.Eq(enterpriseId),
		dao.EnterprisePersonEntity.ID.Eq(req.Id),
	).First()
	if err != nil {
		return "", errors.New("传递主键错误")
	}
	personEntity, err := dao.EnterprisePersonEntity.WithContext(l.ctx).Where(
		dao.EnterprisePersonEntity.EnterpriseID.Eq(enterpriseId),
		dao.EnterprisePersonEntity.Mobile.Eq(req.Mobile),
	).First()
	if !errors.Is(err, gorm.ErrRecordNotFound) && personEntity.ID != req.Id {
		return "", errors.New("手机号码已经存在,不能重复")
	}
	if _, err = dao.EnterprisePersonEntity.WithContext(l.ctx).Where(
		dao.EnterprisePersonEntity.EnterpriseID.Eq(enterpriseId),
		dao.EnterprisePersonEntity.ID.Eq(req.Id),
	).UpdateSimple(
		dao.EnterprisePersonEntity.Name.Value(req.Name),     // 员工姓名
		dao.EnterprisePersonEntity.Mobile.Value(req.Mobile), // 员工手机号码
		dao.EnterprisePersonEntity.Email.Value(req.Email),   // 员工电邮地址
		dao.EnterprisePersonEntity.RoleID.Value(req.RoleID), // 角色id,关联到role表主键
	); err != nil {
		return "", errors.New("修改失败")
	}
	return "修改成功", nil
}
